package com.hzhh123.crypto.filter;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求流转换为多次读取的请求流 过滤器
 * @author hzhh123
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class HttpServletRequestInputStreamFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 转换为可以多次获取流的request
        HttpServletResponse resp = (HttpServletResponse) response;
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {
            requestWrapper =  new InputStreamHttpServletRequestWrapper((HttpServletRequest) request);
        }
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, resp);
        }
    }
}
